<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="style.css" />
  <title>My Blog</title>
</head>

<body>

  <div id="posts-container">
    <div class="post">
      <div class="number">1</div>
      <div class="post-info">
        <h2 class="post-title">sunt aut facere repellat provident occaecati excepturi optio reprehenderit</h2>
        <p class="post-body">quia et suscipit
          suscipit recusandae consequuntur expedita et cum
          reprehenderit molestiae ut ut quas totam
          nostrum rerum est autem sunt rem eveniet architecto</p>
      </div>
    </div>
  </div>

  <div class="loader">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
  </div>
  <script src="./axios.js"></script>
  <script>
    // 获取数据
    async function getMsg(page) {
      try {
        let res = await axios({ url: 'https://jsonplaceholder.typicode.com/posts', params: { _limit: 4, _page: page } })
        return res.data
      } catch (err) {
        console.log(err)
      }
    }

    // 页面渲染
    let pages = 1
    async function showList() {
      document.querySelector('.loader').classList.add('show')
      if (pages === 1) {
        document.querySelector('#posts-container').innerHTML = ''
      }
      let data = await getMsg(pages)
      // console.log(data)
      let str = ''
      if (data) {
        data.forEach(item => {
          str += `
              <div class="post">
                <div class="number">${item.id}</div>
                <div class="post-info">
                  <h2 class="post-title">${item.title}</h2>
                  <p class="post-body">${item.body}</p>
                </div>
              </div>
          `
        })
        document.querySelector('#posts-container').innerHTML += str
      } else {
        console.log('Failed to fetch posts');
      }
      document.querySelector('.loader').classList.remove('show')
    }

    // 下拉滚动刷新
    window.addEventListener('scroll', () => {
      if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
        pages++
        showList()
      }
    })

    showList()
  </script>
</body>

</html>